<?php
if (!function_exists('fnmatch')) {
	function fnmatch($pattern, $string) {
		for ($op = 0, $npattern = '', $n = 0, $l = strlen($pattern); $n < $l; $n++) {
			switch ($c = $pattern[$n]) {
				case '\\':
					$npattern .= '\\' . @$pattern[++$n];
					break;
				case '.': case '+': case '^': case '$': case '(': case ')': case '{': case '}': case '=': case '!': case '<': case '>': case '|':
					$npattern .= '\\' . $c;
					break;
				case '?': case '*':
					$npattern .= '.' . $c;
					break;
				case '[': case ']': default:
					$npattern .= $c;
				if ($c == '[') {
					$op++;
				} else if ($c == ']') {
					if ($op == 0) return false;
					$op--;
				}
				break;
			}
		}		
		if ($op != 0) return false;
		
		return preg_match('/' . $npattern . '/i', $string);
	}
}

$localfolder = $argv[1];
$logfile = "log_js.txt";

$print_file_counts=true;//this can help you find new templates that have not been translated!

$hash_list = array();//The md5 sums mapped to translations

$hash_list_file = array();//The md5 sums mapped to translations
$order   = array("\r\n", "\n", "\r");
$endline ="\r";

$file_word_count = array();// for recording what files have been translated and how may items where in each file
$supportedLanguage = array('vi_VN','en_US');
$defaultLang = 'vi_VN';

$rootfolder = realpath(dirname(__FILE__). '/..');

if (!file_exists($rootfolder."/$localfolder/$defaultLang")) {
	mkdir($rootfolder."/$localfolder/$defaultLang",0777,true);
}

/////////////load key of current file/////
$outFile = realpath(dirname(__FILE__). '/..') ."/$localfolder/jslang/$defaultLang/lang.js";


if (file_exists($outFile)) {
	
	
	$fh = fopen($outFile, 'r') or die("can't open file");
	//LocalizedStrings ["User Name"]	
	
	$patterngetkey = '!LocalizedStrings[\s][\[]["]*(.*?)["][\]]!s';
	if (filesize($outFile) >0) {
		$currentcontent = fread($fh, filesize($outFile));			
		//echo $currentcontent;
		preg_match_all($patterngetkey, $currentcontent, $matcheskey);
		
		foreach($matcheskey[1] as $mkey) {
			$newmkey = str_replace($order, $endline, $mkey);
			$mymd5 = md5($newmkey);
			$hash_list_old[$mymd5]= $newmkey;
			echo $mkey."\n";			
		}
	}
	fclose($fh);
	
}


/////////scan js file for dictionary data/////////


$flog = fopen($logfile, 'w') or die("can't open file");
//grep static text only
$regexjs = '![_][(][\'"](.*?)[\'"][,)]!s';
$patterncheckescape = "![\\\][\"]!s";
$patterncheckescape1 = "![\"]!s";
$hash_list = array();
$comment_hash_list= array();


$file_list=list_directory(realpath(dirname(__FILE__). '/..') ."/$localfolder/js");

foreach($file_list as $file){
	//ignore svn file		
	$path_info = pathinfo($file);
	$ext =    	$path_info['extension'];
	if (fnmatch('*.svn-base',$file) 
			||$ext != 'js') {
		continue;
	}
	
		
	if(filesize($file)==0){
		//do nothing with this file!	
		fwrite($flog, "(IGNORED EMPTY FILE) File name : ".$file."\n");
		
	}else{
		fwrite($flog, "File name : ".$file."\n");
		
		$fp = fopen($file, 'r');
		$content = fread($fp, filesize($file));
		
		preg_match_all($regexjs, $content, $matches);			
		foreach($matches[1] as $m) {
			preg_match_all($patterncheckescape,$m,$matchesEscape);
			preg_match_all($patterncheckescape1,$m,$matchesEscape1);
			if (count($matchesEscape[0]) == 0 && count($matchesEscape1[0]) > 0) {
				$m1 = addslashes($m);
				fwrite($flog, "add slashes : file name[$file] \n original [$m] \n modified [$m1]\n");
				echo  "add slashes : file name[$file] \n original [$m] \n modified [$m1]\n";
			} else {
				$m1 = $m;
			}			
			$newmkey = str_replace($order, $endline, $m1);
			$mymd5 = md5($newmkey);
			if(!array_key_exists($mymd5,$hash_list)){
				if (isset($hash_list_old) && array_key_exists($mymd5,$hash_list_old)) {
					continue;
					
				} else {
					//$hash_list[$mymd5]= '';				
					$hash_list[$mymd5]= $newmkey;
					$countwordsinphp += 1;	
					fwrite($flog, "Add new key: [$mymd5][$newmkey] \n");
				}			
				
				
			}	
			$comment_hash_list[$mymd5][$file] = "File :[".$file."]";
			
		}
	}
}	



//out put to file
//todo $hash_list access by index

if (file_exists($outFile)) {
	$fh = fopen($outFile, 'a') or die("can't open file");	
} else {	
	$fh = fopen($outFile, 'w') or die("can't open file");	
}

$countnum = 1;	
$stringData="";
foreach($hash_list as $hash => $word){
	
	$listfilename = $comment_hash_list[$hash];
	$stringLog.="### num:$countnum, key: [$word] appear in files: ### \n";
	
	if ($listfilename != null) {
		foreach ( $listfilename as $value ) {				     
			$stringLog.="# $value \n";
		}
	}	
	
	$stringData.="LocalizedStrings [\"$word\"] = \"$word\";";	
	$stringData.="\n";	
	$countnum +=1;
	
	
}	

fwrite($fh, $stringData);
fclose($fh);
fwrite($flog, $stringLog);
fclose($flog);


function list_directory($dir) {
	$file_list = '';
	$stack[] = $dir;
	while ($stack) {
		$current_dir = array_pop($stack);
		if ($dh = opendir($current_dir)) {
			while (($file = readdir($dh)) !== false) {
				if ($file !== '.' AND $file !== '..') {
					$current_file = "{$current_dir}/{$file}";
					if (is_file($current_file)) {						
						$file_list[] = "{$current_dir}/{$file}";
					} elseif (is_dir($current_file)) {
						$stack[] = $current_file;
					}
				}
			}
		}
	}
	return $file_list;
}
?>
